<?php

namespace app\business\controller;

use think\Controller;
use Util\SysDb;
use think\Db;
use think\db\Where;

class Order extends Controller
{
    public function ordercount()
    {
        $id = trim(input('param.id'));
        $this->db = new SysDb();
        $one = $this->db->table('order_info')->where(['bus_id' => $id, 'status' => 0])->count();
        $two = $this->db->table('order_info')->where(['bus_id' => $id, 'status' => 1])->count();
        $three = $this->db->table('order_info')->where(['bus_id' => $id, 'status' => 2])->count();
        $four = $this->db->table('order_info')->where(['bus_id' => $id, 'status' => 3])->count();
        $five = $this->db->table('order_info')->where(['bus_id' => $id, 'status' => 4])->count();
        // $six = $this->db->table('order_info')->where(['type' => -1])->lists();
        $data["waitplay"] = $one;
        $data["dispose"] = $two;
        $data["butTheDelivery"] = $three;
        $data["shipping"] = $four;
        $data["finish"] = $five;

        exit(json_encode(['message' => 'succ', 'result' => $data]));
    }

    public function cutaddress()
    {
        $belongTerrace = trim(input('param.belongTerrace'));
        $receiveAddres = trim(input('param.receiveAddress'));
        $receiveAddress = explode(" ", $receiveAddres);
        $this->db = new SysDb();
        $one = $this->db->table('sys_sensitive')->where(['sensitive_str' => $receiveAddress[0]])->item();
        $two = $this->db->table('sys_sensitive')->where(['sensitive_str' => $receiveAddress[1]])->item();
        $three = $this->db->table('sys_sensitive')->where(['sensitive_str' => $receiveAddress[2]])->item();
        $four = $this->db->table('sys_sensitive')->where(['sensitive_str' => $receiveAddress[3]])->item();
        if ($one) {
            $receiveAddress[4] = $one['sensitive_str'];
            exit(json_encode(['message' => 'succ', 'result' => $receiveAddress]));
        }
        if ($two) {
            $receiveAddress[4] = $two['sensitive_str'];
            exit(json_encode(['message' => 'succ', 'result' => $receiveAddress]));
        }
        if ($three) {
            $receiveAddress[4] = $three['sensitive_str'];
            exit(json_encode(['message' => 'succ', 'result' => $receiveAddress]));
        }

        if ($four) {
            $receiveAddress[4] = $four['sensitive_str'];
            exit(json_encode(['message' => 'succ', 'result' => $receiveAddress]));
        }
        $receiveAddress[4] = "";
        exit(json_encode(['message' => 'succ', 'result' => $receiveAddress]));
    }
    public function sendCargo()
    {
        $belongTerrace = trim(input('param.belongTerrace'));
        $expressSheetId = trim(input('param.expressSheetId'));
        $goodsId = trim(input('param.goodsId'));
        $goodsNum = trim(input('param.goodsNum'));
        $recipientInfo = input('param.recipientInfo');
        $recipientInfos = input('param.recipientInfos');
        $recipientInfolen = trim(input('param.recipientInfolen'));
        $remark = trim(input('param.remark'));
        $shopId = trim(input('param.shopId'));
        $importType = trim(input('param.importType'));
        $userid = trim(input('param.userid'));
        $cost = trim(input('param.cost'));
        $profit = trim(input('param.profit'));
        $level = trim(input('param.level'));
        $pklist = array();
        $this->db = new SysDb();
        $one = $this->db->table('goods_info')->where(['id' => $goodsId])->item();
        if ($goodsNum < 1) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "礼物数量最少一件"]));
        }
        if ($goodsNum > $one["repertory"]) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "礼物数量多余库存"]));
        }
        if ($belongTerrace < 1 || $belongTerrace > 5) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "数据来源平台错误"]));
        }
        if ($importType < 1 || $importType > 6) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "导入方式错误"]));
        }
        $this->db = new SysDb();
        $one = $this->db->table('goods_info')->where(['id' => $goodsId])->item();
        if (null == $one) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "礼品不存在"]));
        }
        if (floatval($one['status']) != 1) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "该礼品未处于上架状态"]));
        }
        if (floatval($one['repertory']) < 1) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "礼品库存不足"]));
        }

        $two = $this->db->table('sys_express_sheet')->where(['id' => $expressSheetId])->item();
        if (null == $two) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "快递信息不存在"]));
        }
        if ($two['store_id'] != $one['store_id']) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "面单的仓库与商品的仓库不匹配，请重新选择面单"]));
        }

        $three = $this->db->table('goods_store')->where(['id' => $one['store_id']])->item();
        if (floatval($three['status']) != 1) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => floatval($three['status'])]));
        }
        $four = $this->db->table('tenant_goods_price')->where(['tenant_id' => 1])->where(['goods_id' => $goodsId])->lists();
        if ($four == null) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "礼品价格获取失败"]));
        }
        $five = $this->db->table('sys_sensitive')->lists();
        $fivelen = $this->db->table('sys_sensitive')->count();
        //价格
        $goodsPrice = floatval($cost) + floatval($profit);
        //单个包裹商品总价
        $goodsAmount = $goodsPrice * floatval($goodsNum);
        //计算礼品总费用
        $totalgoodsAmount = $goodsAmount * floatval($recipientInfolen);
        $weight = floatval($one['weight']) * floatval($goodsNum);

        $expressInfo = $this->GetExpressAmount($expressSheetId, $weight, 1, $level);
        $expressAmount = $expressInfo['expressAmount'];
        $tenantExpressProfit = $expressInfo['tenantProfit'];
        $tenantExpressCost = $expressInfo['tenantCost'];
        $expressCost = $expressInfo['cost'];
        $Discount = $expressInfo['discount'];
        if ($expressAmount < 0 || $tenantExpressProfit < 0) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "价格设置有误，请联系客服"]));
        }
        $totalExpressAmount = intval($recipientInfolen) * floatval($expressAmount);
        $pkAmount = floatval($goodsAmount) + floatval($expressAmount);
        $tenantProfit = (floatval($tenantExpressProfit) + floatval($four[0]['profit'])) * $Discount;
        if ($tenantProfit < 0) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "价格设置有误，请联系客服"]));
        }
        //管理员的快递费用为负或商品利润为负，则无法下单(未写)
        //初始化订单


        $a = range(0, 9);
        for ($i = 0; $i < 10; $i++) {
            $b[] = array_rand($a);
        }
        $order['id'] = join("", $b);
        $order['tenant_id'] = 1;
        $order['bus_id'] = $userid;
        $order['bus_parent_id'] = 0;
        $order['store_id'] = $one['store_id'];
        $order['goods_id'] = $goodsId;
        $order['pk_count'] = floatval($recipientInfolen);
        $order['goods_count'] = floatval($recipientInfolen) * floatval($goodsNum);
        $order['goods_amount'] = $totalgoodsAmount;
        $order['express_amount'] = $totalExpressAmount;
        $order['belong_terrace'] = $belongTerrace;
        $order['import_type'] = $importType;
        $order['remark'] = $remark;
        $order['express_sheet_id'] = $expressSheetId;
        $order['other_type'] = 1;
        $order['other_status'] = -1;
        $order['other_status'] = floatval($recipientInfolen) * $goodsAmount;
        $order['shop_id'] = $shopId;
        $order['amount'] = $totalgoodsAmount + $totalExpressAmount;

        // $this->db->table('order_info')->insert($order);
        // exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $recipientInfo]));
        // exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $order]));

        foreach ($recipientInfos as  $recipientInfoitem) {


            // exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $recipientInfoitem]));

            $pk['id'] = floatval($recipientInfoitem['orderNo']);
            $pk['province'] = $recipientInfoitem['province'];
            $pk['city'] = $recipientInfoitem['city'];
            $pk['county'] = $recipientInfoitem['county'];
            $pk['address'] = $recipientInfoitem['address'];
            $pk['name'] = $recipientInfoitem['name'];
            $pk['phone'] = $recipientInfoitem['phone'];
            $pk['order_no'] = floatval($recipientInfoitem['orderNo']);
            $pk['trade_name'] = null;
            $pk['encrypt_address'] = null;
            $pk['encrypt_name'] = null;
            $pk['encrypt_phone'] = null;
            $pk['remark'] = null;
            $pk['express_sheet_id'] = $expressSheetId;
            $pk['express_company'] = $two['shipper_name'];
            $pk['order_id'] = $order['id'];
            $pk['template_status'] = $two['express_status'];
            $pk['spread_profit'] = 0;
            $pk['weight'] = $weight;
            $pk['goods_id'] = $goodsId;
            $pk['store_id'] = $two['store_id'];
            $pk['goods_remark'] = $one['name'];
            $pk['goods_num'] = floatval($goodsNum);
            $pk['tenant_profit'] = floatval($tenantExpressProfit);
            $pk['profit'] = $tenantProfit;
            $pk['amount'] = $pkAmount;
            $pk['auto_status'] = 0;
            $pk['other_type'] = 1;
            $pk['tenant_id'] = 1;
            $pk['bus_id'] = $userid;
            $pk['bus_parent_id'] = 0;
            $pk['belong_terrace'] = $belongTerrace;
            if ($pk['order_no'] == null) {
                exit(json_encode(['code' => 1, 'message' => 'error', "result" => "收件人信息第" + $i + "行数据解析失败"]));
            }
            if ($pk['province'] == null || $pk['city'] == null || $pk['county'] == null || $pk['address'] == null || $pk['name'] == null || $pk['phone'] == null) {
                exit(json_encode(['code' => 1, 'message' => 'error', "result" => "收件人信息第" + $i + "行数据解析失败"]));
            }
            $tmparray = explode("*", $pk['phone']);
            if (count($tmparray) > 1) {
                exit(json_encode(['code' => 1, 'message' => 'error', "result" => "收件人信息第" + $i + "行数据解析失败,手机号码不能带*号"]));
            }
            for ($k = 0; $k < $fivelen; $k++) {
                $tmparray = explode($five[$k]['sensitive_str'], $recipientInfo);
                if (count($tmparray) > 1) {
                    exit(json_encode(['code' => 1, 'message' => 'error', "result" => "收件人信息第" + $i + "行数据解析失败, 【" + $five[$k] + "】为敏感词，禁止发货"]));
                }
            }
            $six = $this->db->table('pk_info')->where(['order_no' => $pk['order_no']])->lists();
            if ($six) {
                exit(json_encode(['code' => 1, 'message' => 'error', "result" => "第" + $i + "行编号已经存在"]));
            }

            array_push($pklist, $pk);
            // $this->db->table('pk_info')->insert($pk);
        }
        //  $this->db->table('pk_info')->insertAll($pklist);
        // exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $pklist]));

        $seven = $this->db->table('bus_info')->where(['id' => $userid])->item();
        if ($seven['balance'] < $totalgoodsAmount) {
            $order['status'] = 0;
            foreach ($pklist as  $k => &$value) {
                $value["status"] = 0;
            }
            $this->db->table('pk_info')->insertAll($pklist);
            $this->db->table('order_info')->insert($order);
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "余额不足, 已将任务暂存到订单列表中, 充值完成后可到订单列表中完成支付"]));
        } else {
            $order['status'] = 1;
            $order['pay_time'] = date("Y-m-d H:i:s", time());
            foreach ($pklist as  $k => &$value) {
                $value['status'] = 1;
            }
            $this->db->table('pk_info')->insertAll($pklist);
            $this->db->table('order_info')->insert($order);

            $seven['balance'] = floatval($seven['balance']) - floatval($totalgoodsAmount);
            $this->db->table('bus_info')->where(['id' => $userid])->update($seven);
            $data['tenant_id'] = 1;
            $data['bus_id'] = $userid;
            $data['amount'] = $totalgoodsAmount + $totalExpressAmount;
            $data['type'] = 2;
            $data['deal_type'] = 2;
            $data['deal_desc'] = "下单支出";
            $data['remark'] = "下单支出";
            $data['create_time'] = date("Y-m-d H:i:s", time());
            $this->db->table('bus_flow')->insert($data);
            
            $tenant = $this->db->table('tenant_goods_price')->where(['goods_id' => $goodsId])->item();
            $profitg['tenant_id']=trim(input('param.tenantId'));
            $profitg['deal_type']=1;
            $profitg['origin']="客户下单";
            $profitg['money']=$tenant['tenant_profit'];
            $profitg['remark']="客户下单";
            $profitg['status']=1;
            $this->db->table('tenant_profit')->insert($profitg);
            $profits['deal_type']=1;
            $profits['origin']="客户下单";
            $profits['money']=$tenant['profit'];
            $profits['remark']="客户下单";
            $profits['status']=1;
            $this->db->table('ad_profit')->insert($profits);
            $flow['tenant_id']=trim(input('param.tenantId'));
            $flow['type']=1;
            $flow['deal_type']=1;
            $flow['deal_desc']="客户下单";
            $flow['money']=$data['amount'];
            $flow['remark']="客户下单";
            $flow['status']=1;
            $this->db->table('tenant_flow')->insert($flow);
            $flows['type']=1;
            $flows['money']=$tenant['profit'];
            $flows['remark']="客户下单";
            $flows['status']=1;
            $this->db->table('ad_flow')->insert($flows);
            $summany= DB::name("sys_summary")->order("id desc")->find();
            $idw=$summany['id'];
            $arraym=explode(" ",$summany['create_time']);
            if($arraym[0]==date("Y-m-d")){
                $summany['profit']=$summany['profit']+$tenant['profit'];
                $summany['tenant_profit']=$summany['tenant_profit']+$tenant['tenant_profit'];
                $summany['order_num']=$summany['order_num']+1;
                $summany['pk_num']=$summany['pk_num']+floatval($recipientInfolen);
                $this->db->table('sys_summary')->where(['id' => $idw])->update($summany);
            }
            else{
                $summany['id']=$summany['id']+1;
                $summany['tenant_id']=trim(input('param.tenantId'));
                $summany['bus_num']=0;
                $summany['recharge']=0;
                $summany['order_num']=1;
                $summany['pk_num']=floatval($recipientInfolen);
                $summany['profit']=$tenant['profit'];
                $summany['tenant_profit']=$tenant['tenant_profit'];
                $summany['create_time']=date('Y-m-d h:i:s', time());;
                $this->db->table('sys_summary')->insert($summany);
            }
            exit(json_encode(['code' => 1, 'message' => 'succ', "result" => "下单成功"]));
            
        }
    }
    function GetExpressAmount($expresssheetid, $weight, $tenantid, $tenantviplevel)
    {
        $outAmount = "";
        $expressSheetId = $expresssheetid;
        $tenantId = $tenantid;
        $Weight = $weight;
        $tenantVipLevel = $tenantviplevel;
        $this->db = new SysDb();
        $sysExpressFee = $this->db->table('sys_express_fee')->where(['express_sheet_id' => $expressSheetId])->item();
        if (floatval($sysExpressFee['max_weight']) < $weight) {
            $outWeight = $Weight - floatval($sysExpressFee['max_weight']);
            $outAmount = $outWeight * 1;
        }
        $tenantExpressFeeList = Db::table('tenant_express_fee')
            ->alias(' tef')
            ->join('sys_express_fee sef', 'tef.express_fee_id = sef.id', "left")
            ->join('tenant_vip_level tvl', 'tvl.tenant_id = tef.tenant_id', "left")
            ->where(['express_sheet_id' => $expressSheetId])
            ->where(['tef.tenant_id' => $tenantId])
            ->where(['name' => $tenantVipLevel])
            ->field(array(' tef.id', 'tef.profit', 'tef.cost' => "tenantCost", 'sef.cost', 'sef.max_weight', 'sef.express_sheet_id' => 'expressSheetId', "tvl.discount", "tvl.tenant_id"))
            ->select();

        if (!$tenantExpressFeeList) {
            exit(json_encode(['code' => 1, 'message' => 'error', "result" => "快递费用获取失败"]));
        }
        $tenantExpressFee = $tenantExpressFeeList[0];
        // exit(json_encode(['code' => 1, 'message' => 'succ', "result" =>$tenantExpressFee]));
        $expressAmount = floatval($tenantExpressFee["profit"]) + floatval($tenantExpressFee['cost']);
        if (null != $outAmount) {
            $expressAmount = floatval($expressAmount) + floatval($outAmount);
        }
        $expressAmount = $expressAmount * floatval($tenantExpressFee['discount']);
        $result['expressAmount'] = round(($expressAmount), 2);
        $result['tenantProfit'] = floatval($tenantExpressFee['profit']);
        $result['tenantCost'] = floatval($tenantExpressFee['tenantCost']);
        $result['cost'] = floatval($tenantExpressFee['cost']);
        $result['discount'] = floatval($tenantExpressFee['discount']);
        return $result;
    }
    function newList()
    {
        $id = trim(input('param.id'));
        $type = trim(input('param.status'));
        $bus_id = trim(input('param.bus_id'));
        $page = trim(input('param.pageNo'));
        $limit = trim(input('param.pageSize'));
        $this->db = new SysDb();
        // $count = $this->db->table('newslist')->count();
        $tol = (intval($page) - 1) * $limit;
        $where=array(
            "id" => $bus_id,
            "bus_id" => $id,
            "status" => $type,
        );
        foreach ($where as $key=>$value)
        {
            if(empty($value)){
                unset($where[$key]);
            }
        }
        $list = DB::name("order_info")->order("create_time desc")->where($where)->limit($tol, $limit)->select();
        // $list=$this->db->table('order_info')->where(['bus_id' =>$id])->lists();
        exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $list]));
    }
    function listCount()
    
    {
        
        $id = trim(input('param.id'));
        $type = trim(input('param.status'));
        $bus_id = trim(input('param.bus_id'));
        $this->db = new SysDb();
        $where=array(
            "id" => $bus_id,
            "bus_id" => $id,
            "status" => $type,
        );
        foreach ($where as $key=>$value)
        {
            if(empty($value)){
                unset($where[$key]);
            }
        }
        $newlist = $this->db->table('order_info')->where($where)->count();
        exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $newlist]));
    }
    function pknewList()
    {
        $id = trim(input('param.orderId'));
        $page = trim(input('param.pageNo'));
        $limit = trim(input('param.pageSize'));
        $this->db = new SysDb();
        // $count = $this->db->table('newslist')->count();
        $tol = (intval($page) - 1) * $limit;

        $list = DB::name("pk_info")->where('order_id', $id)->limit($tol, $limit)->select();
        // $list=$this->db->table('order_info')->where(['bus_id' =>$id])->lists();
        exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $list]));
    }
    function pklistCount()
    {
        $id = trim(input('param.id'));
        $this->db = new SysDb();
        $newlist = $this->db->table('pk_info')->where(['order_id' => $id])->count();
        exit(json_encode(['code' => 1, 'message' => 'succ', "result" => $newlist]));
    }
    function cancel()
    {
        $id = trim(input('param.orderId'));
        $this->db = new SysDb();
        $one = $this->db->table('order_info')->where(['id' => $id])->delete();
        $two = $this->db->table('pk_info')->where(['order_id' => $id])->delete();
        if ($one || $two) {
            exit(json_encode(['code' => 1, 'message' => 'succ', "result" => "订单已取消"]));
        }
    }

    function pay()
    {
        $id = trim(input('param.orderId'));
        $this->db = new SysDb();
        $one = $this->db->table('order_info')->where(['id' => $id])->item();
        $two = $this->db->table('bus_info')->where(['id' => $one['bus_id']])->item();
        $pk = $this->db->table('pk_info')->where(['order_id' => $id])->item();
        if ($one['amount'] <= $two['balance']) {
            $two['balance'] = $two['balance'] - $one['amount'];
            $three = $this->db->table('bus_info')->where(['id' => $one['bus_id']])->update($two);
            if ($three) {
                $code = '';
                for ($i = 1; $i < 11; $i++) {         //通过循环指定长度
                    $randcode = mt_rand(0, 9);     //指定为数字
                    $code .= $randcode;
                }
                $one['status']=2;
                $one['pay_time']=date('Y-m-d h:i:s', time());
                $pk['express_no']=$code;
                $pk['status']=1;
                $four = $this->db->table('order_info')->where(['id' => $id])->update($one);
                $five = $this->db->table('pk_info')->where(['order_id' =>$id])->update($pk);
                if($four||$five){
                    exit(json_encode(['code' => 1, 'message' => 'succ', "result" => "订单支付成功"]));
                }
               
            }
        }
    }
}
